package com.codingday.app;

import java.text.SimpleDateFormat;
import java.util.List;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class TODOView extends MapActivity {

	TextView tv_title;
	TextView tv_desc;
	//TextView tv_date;
	TextView tv_location;
	TextView tv_createdDate;
	TextView tv_completedDate;
	//int position;
	
	ToggleButton tb_enabled;
	
	TODO todo;
	
	// for Map Display
	double latitude;
	double longitude;
	int radius;
	
	MapView googleMap;
	MapController mc;
	List<Overlay> mapOverlays;
	
	Criteria cta;
	LocationManager locationManager;
	String provider;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		

		setContentView(R.layout.viewtodo);
		
		Intent intent = getIntent();
		
		//int position = intent.getIntExtra("position", 0);		
		//Log.i("TODOView","position : "+position);
		long ID = intent.getLongExtra("TODOID", -1);
		todo = TODOListManager.getTODO(ID);
		if(todo == null){
			Log.i("TODOView","TODO is NULL of ID : "+ ID);
		}
		
		tv_title = (TextView) findViewById(R.id.view_todo_title_text);
		tv_desc = (TextView) findViewById(R.id.view_todo_desc_text);
		tv_location = (TextView) findViewById(R.id.view_todo_location);
		tv_createdDate = (TextView) findViewById(R.id.view_todo_createdDate);
		tv_completedDate = (TextView) findViewById(R.id.view_todo_completedDate);
		initTextButtons();
		initToggleButton();
		initMap();
	}
	
	public void initToggleButton(){
		tb_enabled = (ToggleButton)findViewById(R.id.view_todo_toggle_button);
		tb_enabled.setChecked(todo.isEnabled());
		
		if(todo.isCompleted()){
			tb_enabled.setEnabled(false);
		}
		
		tb_enabled.setOnCheckedChangeListener(new OnCheckedChangeListener(){

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				// TODO Auto-generated method stub
				if(isChecked){
					todo.Enable();
				}else{
					todo.Disable();
				}
			}
			
		});
	}
	
	public void initTextButtons(){
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//Log.i("TODOVIew","Title("+position+") : " + todo.getTitle());
		tv_title.setText(todo.getTitle());
		//tv_createdDate.setText("Created Date : "+todo.isCompleted()?"dateFormat.format(todo.getCompletedDate()));
		tv_desc.setText(todo.getDesc()+(todo.isPausedByInitial()?" : paused":""));//+" ID:"+todo.getID());
		latitude = todo.getLatitude();
		longitude = todo.getLongitude();
		radius = todo.getRadius();
		tv_location.setText(""+todo.getLatitude()+","+todo.getLongitude() +"-" + todo.getRadius() +"m");
		
		tv_createdDate.setText("Created:"+dateFormat.format(todo.getCreatedDate()));
		if(todo.isCompleted()){
			tv_completedDate.setText("Completed:"+dateFormat.format(todo.getCompletedDate())+"\n");
		}else{
			tv_completedDate.setText("\n");
		}
		
	}
	
	public void initMap(){
		googleMap = (MapView) findViewById(R.id.todoview_map);
		locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

		checkProvider();
		
		//googleMap.setSatellite(true);
		googleMap.setStreetView(true);
		googleMap.setBuiltInZoomControls(true);
		

		mc = googleMap.getController();

		GeoPoint p = new GeoPoint((int)(latitude*1E6), (int)(longitude * 1E6));
		mc.animateTo(p);
		mc.setZoom(16);
		
		mapOverlays = googleMap.getOverlays(); 
		mapOverlays.add(new OverlayCircle());
		
	}
	
	public void checkProvider() {
	       locationManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
	       cta=new Criteria();
	       cta.setAccuracy(Criteria.ACCURACY_FINE);
	       cta.setPowerRequirement(Criteria.POWER_HIGH);
	       cta.setAltitudeRequired(false);
	       cta.setSpeedRequired(false);
	       cta.setCostAllowed(false);
	       provider = locationManager.getBestProvider(cta, true);
	}
	
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		//super.onBackPressed();
		goBackToList();
	}
	
	public void goBackToList(){
		Intent result = new Intent();
		result.putExtra("result", true);
		setResult(Activity.RESULT_OK, result);	
		finish();		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
    	boolean result = super.onCreateOptionsMenu(menu);
    	
    	MenuInflater menuInflator = new MenuInflater(this);
    	//menuInflator.inflate(R.layout.main_menu, menu);
    	

    	if(todo.isCompleted()){
        	menuInflator.inflate(R.menu.done_view_menu, menu);
    	}else{
        	menuInflator.inflate(R.menu.view_menu, menu);    		
    	}
    	return result;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		boolean result =  super.onOptionsItemSelected(item);
		
		if(todo.isCompleted() == false){
			switch(item.getItemId())
			{
				case R.id.view_menu_edit :
					TODOListView.getInstance().gotoEditToDoActivity(todo.getID());
					break;
				case R.id.view_menu_done:
					todo.setCompleted(true);
					goBackToList();
					break;
				case R.id.view_menu_delete:
					DeleteDialog();	
					break;
				default:
					break;
			}
		}else{
			switch(item.getItemId())
			{
				case R.id.view_menu_reuse :
					Log.i("TODOView","Re-Use it");
					todo.setCompleted(false);
					goBackToList();
					break;
				case R.id.view_menu_delete:
					DeleteDialog();
					break;
				default:
					break;
			}			
		}
		
		return result;
	}
    
	private void DeleteDialog(){
		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setMessage("Do you want to delete this TODO ?")
			.setCancelable(false).setPositiveButton("Yes",
					new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// Action for 'Yes' Button
						Toast.makeText(getApplicationContext(), "Delete", 1);
						TODOListManager.deleteTODO(todo.getID());
						goBackToList();
					}
			})
			.setNegativeButton("No",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							// Action for 'NO' Button
							dialog.cancel();
						}
			});
		AlertDialog alert = alt_bld.create();
		
		// Title for AlertDialog
		//alert.setTitle("Title");
		// Icon for AlertDialog
		//alert.setIcon(R.drawable.icon);
		alert.show();
	}
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
    	
	
	private class OverlayCircle extends Overlay{

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			// TODO Auto-generated method stub
			super.draw(canvas, mapView, shadow);
			 Paint paint1 = new Paint();
		     //Paint paint2 = new Paint();

		     paint1.setARGB(56, 200, 0, 255); // a, r, g, b
		     //paint2.setARGB(255, 255, 0,0);

		     GeoPoint geoPoint = new GeoPoint((int)(latitude*1E6), (int)(longitude*1E6)); 
		     Point pixPoint = new Point(); 
		     mapView.getProjection().toPixels(geoPoint, pixPoint); 
		     
		     int radiusR = metersToRadius(radius, mapView, latitude);
		     canvas.drawCircle(pixPoint.x, pixPoint.y, radiusR, paint1);
		     
		     Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ping);
		     canvas.drawBitmap(bmp, pixPoint.x-bmp.getWidth()/2, pixPoint.y-bmp.getHeight(), null); 
		     
		}
		
	}
	

	public static int metersToRadius(float meters, MapView map, double latitude) {
	    return (int) (map.getProjection().metersToEquatorPixels(meters) * (1/ Math.cos(Math.toRadians(latitude))));         
	}

}
